package com.lms.netty.protobuf;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-18 10:40
 * @Description:
 */
public class ProtobufNettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(1).setName("豹子头 林冲").setAge(30).build();
//        ctx.writeAndFlush(student);

        int i = new Random().nextInt(3);
        MyDataInfo.MyMessage message=null;
        if (i==0){
             message = MyDataInfo.MyMessage.newBuilder()
                    .setType(MyDataInfo.MyMessage.DataType.StudentType)
                    .setStudent(MyDataInfo.Student.newBuilder().setId(1).setName("李四"))
                    .build();
        }else {
            message = MyDataInfo.MyMessage.newBuilder()
                    .setType(MyDataInfo.MyMessage.DataType.TeacherType)
                    .setTeacher(MyDataInfo.Teacher.newBuilder().setId(2).setName("xxx").setJob("主任"))
                    .build();
        }
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器回复的消息："+((ByteBuf)msg).toString(StandardCharsets.UTF_8));
        System.out.println("服务器的地址："+ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }

}
